package com.woniuxy.yoga.order.service.mq;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.woniuxy.yoga.commons.alipay.data.PayStateResponseParam;
import com.woniuxy.yoga.commons.alipay.util.AlipayUtil;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.commons.core.statedata.CoachState;
import com.woniuxy.yoga.commons.core.statedata.OrderState;
import com.woniuxy.yoga.order.client.CoachClient;
import com.woniuxy.yoga.order.client.ProductClient;
import com.woniuxy.yoga.order.dao.mapper.OrderInfoMapper;
import com.woniuxy.yoga.order.dao.model.OrderInfo;
import com.woniuxy.yoga.order.model.dto.Coach;
import com.woniuxy.yoga.order.model.dto.PrivateProductByIdDTO;
import com.woniuxy.yoga.order.model.dto.TeamProductByIdDTO;
import com.woniuxy.yoga.order.model.exception.OrderException;
import com.woniuxy.yoga.order.model.exception.OrderExceptionCode;
import com.woniuxy.yoga.order.service.OrderInfoService;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class HandlerOrderConsumer {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private AlipayUtil alipayUtil;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ProductClient productClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CoachClient coachClient;

    @RabbitListener(
            bindings = {
                    @QueueBinding(
                            value = @Queue(name = "order-queue"),
                            exchange = @Exchange(name = "order-delay-ex"),
                            key = "order"
                    )
            }
    )
    @Transactional
    public void handler(String orderNum) throws Exception{
        //消费队列中的订单
        //调用支付宝的接口判断本次订单的支付状态
        PayStateResponseParam payStateResponseParam = alipayUtil.selPayState(orderNum);
        OrderInfo orderInfo = orderInfoMapper.selectById(orderNum);
        String payDate = DateUtil.format(payStateResponseParam.getSendPayDate(),"yyyy-MM-dd HH:mm:ss");
        if (orderInfo!=null){
            if ("TRADE_SUCCESS".equals(payStateResponseParam.getTradeStatus())){
                //修改订单状态
                orderInfo.setOrderState(OrderState.ORDER_STATE_PAYED);
                orderInfo.setOrderPayTime(payDate);
                orderInfoMapper.updateById(orderInfo);
                //生成当前产品进度表
                //1.普通课程
                if (orderInfo.getTypes()==OrderState.ORDER_PRODUCT_TYPE_NORMAL){
                    //体验卡课程
                    if (orderInfo.getProductTypeId() == OrderState.PRODUCT_TYPE_ID_EXPERIENCE){
                        //调用创建方法
                        orderInfoService.createExpCard(orderInfo.getOrderNum(),orderInfo.getUserId());
                    }
                    //次卡课程
                    if (orderInfo.getProductTypeId() == OrderState.PRODUCT_TYPE_ID_TIMES){
                        //调用创建方法
                        orderInfoService.createSubCard(orderInfo.getOrderNum(),orderInfo.getOrderCount(),orderInfo.getUserId());
                    }
                    //月卡课程
                    if (orderInfo.getProductTypeId() == OrderState.PRODUCT_TYPE_ID_MONTHS){
                        //调用创建方法
                        orderInfoService.createMonCard(orderInfo.getOrderNum(),payDate,orderInfo.getOrderCount(),orderInfo.getUserId());
                    }
                    //终身卡课程
                    if (orderInfo.getProductTypeId() == OrderState.PRODUCT_TYPE_ID_INFINITY){
                        //调用创建方法
                        orderInfoService.createLifeCard(orderInfo.getOrderNum(),orderInfo.getUserId());
                    }
                }
                //2.团课课程
                if (orderInfo.getTypes() == OrderState.ORDER_PRODUCT_TYPE_TEAM){
                    Result<TeamProductByIdDTO> result = productClient.getByTeamProductId(orderInfo.getProductId());
                    if (result.getCode()!=200) throw new OrderException(result.getCode(),result.getMessage());
                    TeamProductByIdDTO teamProductByIdDTO = result.getData();
                    //调用创建方法
                    orderInfoService.createTeaCard(orderInfo.getOrderNum(),teamProductByIdDTO.getHourCount(),orderInfo.getUserId());
                }
                //3.私教课
                if (orderInfo.getTypes() == OrderState.ORDER_PRODUCT_TYPE_COACH){
                    //查询私教产品信息获取教练id
                    Result<PrivateProductByIdDTO> result = productClient.getByPrivateProductId(orderInfo.getProductId());
                    if (result.getCode()!=200) throw new OrderException(result.getCode(),result.getMessage());
                    PrivateProductByIdDTO privateProductByIdDTO = result.getData();
                    //判断教练状态
                    Result<Coach> coachResult = coachClient.getByCoachId(privateProductByIdDTO.getCoachId());
                    if (coachResult.getCode()!=200) throw new OrderException(coachResult.getCode(),coachResult.getMessage());
                    if (coachResult.getData().getCoachState()!= CoachState.COACH_STATE_NORMAL)
                        throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_COACH_STATE_WRONG);
                    //调用创建方法
                    orderInfoService.createPriCard(orderInfo.getOrderNum(),privateProductByIdDTO.getCoachId(),orderInfo.getOrderCount(),orderInfo.getUserId());
                }
                //设置定时任务，15天用户未评价系统默认好评
                //设置定时任务 到时自动将状态修改成已开课 创建json数据
                Map<String, Object> map = new HashMap<>();
                map.put("orderNum",orderInfo.getOrderNum());
                //转json字符串
                String orderNumXXL = JSONUtil.toJsonStr(map);
                //设置定时任务
                String xxlLoginAPI="http://192.168.90.27:9999/xxl-job-admin/login";
                String xxlAddJobAPI="http://192.168.90.27:9999/xxl-job-admin/jobinfo/add";
                HashMap<String, Object> loginParam = new HashMap<String,Object>();
                loginParam.put("userName", "admin");
                loginParam.put("password", "123456");
                HttpResponse httpResponse = HttpRequest.post(xxlLoginAPI).form(loginParam).execute();
                if(httpResponse.getStatus()!=200) {
                    throw new Exception("登录失败");
                }
                Map<String, Object> addTaskParam = new HashMap<String,Object>();
                addTaskParam.put("jobGroup", 5);
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime executeTime = now.plusDays(15L);
                int year = executeTime.get(ChronoField.YEAR);
                int month = executeTime.get(ChronoField.MONTH_OF_YEAR);
                int day = executeTime.get(ChronoField.DAY_OF_MONTH);
                int hour=executeTime.get(ChronoField.HOUR_OF_DAY);
                int minute=executeTime.get(ChronoField.MINUTE_OF_HOUR);
                int second=executeTime.get(ChronoField.SECOND_OF_MINUTE);
                StringBuilder cron = new StringBuilder();
                cron.append(second);
                cron.append(" "+minute);
                cron.append(" "+hour);
                cron.append(" "+day);
                cron.append(" "+month);
                cron.append(" ?");
                cron.append(" "+year);
                addTaskParam.put("scheduleConf", cron.toString());
                addTaskParam.put("jobDesc", "系统自动评价");
                addTaskParam.put("author", "Zachary");
                addTaskParam.put("executorHandler", "orderExpire");
                addTaskParam.put("executorParam",orderNumXXL);//订单编号
                addTaskParam.put("scheduleType", "CRON");
                addTaskParam.put("executorRouteStrategy", "FIRST");
                addTaskParam.put("executorBlockStrategy", "SERIAL_EXECUTION");
                addTaskParam.put("glueType", "BEAN");
                addTaskParam.put("misfireStrategy","DO_NOTHING");
                addTaskParam.put("executorTimeout", "0");
                addTaskParam.put("executorFailRetryCount","0");
                addTaskParam.put("triggerStatus", 1);
                HttpResponse response = HttpRequest.post(xxlAddJobAPI).form(addTaskParam).execute();
                //消息队列生成订单支付完成日志
                Map<String, Object> logMap = new HashMap<>();
                logMap.put("orderNum",orderInfo.getOrderNum());
                logMap.put("logUser",orderInfo.getUserName());
                logMap.put("storeId",orderInfo.getStoreId());
                logMap.put("logTime",payDate);
                logMap.put("logDesc","完成支付");
                rabbitTemplate.convertAndSend("orderInfoNotify.log",logMap);
            }else {//未支付
                //修改状态
                orderInfo.setOrderState(OrderState.ORDER_STATE_CANCEL);
                orderInfoMapper.updateById(orderInfo);
            }
        }
    }
}
